package apps.softtech.fastmarket;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.android.gms.internal.md;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;

import android.widget.Toast;
import apps.softtech.Utility.ApplicationConstants;
import apps.softtech.Utility.ConnectionDetector;
import apps.softtech.Utility.HttpRequest;
import apps.softtech.Utility.RequestDataFromServer;
import apps.softtech.fastmarket.model.UserInfo;

public class ActivityLogin extends Activity {

	private EditText edtUsername, edtPassword;
	private Button btnSignup, btnSignin, btnForgetPassowrd;

	private String mUsername, mPassword;
	private Context mContext;
	private ConnectionDetector mDetector;
	ProgressDialog progress;
	
	Dialog mDialog;
	
//	private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
	private static final String URL_LOGIN = ApplicationConstants.BASE_URL + "users/login/";
	protected static final String TAG = "AcitivityLoginTag";

	private int userIdLoggedIn ;
	protected SharedPreferences pref;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_main_login);
		mContext = this;
		init();
		getEvent();
	}

	private void getEvent() {

		btnSignin.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (checkUserName() && checkPassword()) {
					if (checkInternetConnection()) {
						SignIn(ApplicationConstants.RED_ID, edtUsername.getText().toString(), edtPassword.getText().toString());
					}
				}
			}
		});

		btnSignup.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(mContext, ActivityRegister.class);
				startActivity(intent);
				ActivityLogin.this.finish();
			}
		});
		
		btnForgetPassowrd.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				mDialog.show();
			}
		});
	}

	/**
	 * post info server to login
	 * 
	 * @param username
	 * @param password
	 */

	@SuppressWarnings({ "unchecked", "unused" })
	private void SignIn(String gcmId, String username, String password) {

		final boolean check = false;
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		JSONObject jsonOject = new JSONObject();
		try {
			jsonOject.put(UserInfo.GCMID, gcmId);
			jsonOject.put(UserInfo.USERNAME, username);
			jsonOject.put(UserInfo.PASSWORD, password);

		} catch (JSONException e) {
			e.printStackTrace();
		}
		params.add(new BasicNameValuePair("data", jsonOject.toString()));

		new AsyncTask<List<NameValuePair>, Void, String>() {

			protected void onPreExecute() {
				progress = new ProgressDialog(mContext);
				progress.setMessage("logining ...");
				progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
				progress.setIndeterminate(true);
				progress.show();

			};

			@Override
			protected String doInBackground(List<NameValuePair>... params) {
				HttpRequest request = new HttpRequest();
				String result = request.makeServiceCall(URL_LOGIN,
						HttpRequest.POST, params[0]);
				Log.i(TAG,result);
				return result;
			}

			@Override
			protected void onPostExecute(String result) {
				super.onPostExecute(result);
				progress.dismiss();
				Log.i(TAG, "onpostExecute");

				try {
					JSONObject json = new JSONObject(result);

					if (json.getString("success") != null) {
						String check = json.getString("success");
						Log.i(TAG, "check : " + check);
						if (Integer.parseInt(check) == 1) {
							Toast.makeText(mContext, "Login thanh cong",
									Toast.LENGTH_SHORT).show();

							/*
							 * login thanh cong thi save userId vao bien pref
							 */

							JSONObject jsonData = json.getJSONObject("data");
							userIdLoggedIn = jsonData.getInt("st_UserId");
							Log.i(TAG, "userIdLoggedIn : " + userIdLoggedIn);
							pref = getSharedPreferences("market_data",MODE_PRIVATE);
							SharedPreferences.Editor edit = pref.edit();
							edit.putInt(UserInfo.USERID, userIdLoggedIn);
							edit.commit();
							if(pref.contains(UserInfo.USERID)){
								Log.i(TAG,"co roi");
							}

							/*
							 * chuyen sang trang home
							 */
							Intent intent = new Intent(mContext,
									ActivityDashboard.class);
							startActivity(intent);
							finish();

						} else if (Integer.parseInt(check) == 0) {
							Toast.makeText(mContext,
									"Username hoac mat khau khong dung",
									Toast.LENGTH_SHORT).show();
						}
					} else {
						Toast.makeText(mContext, "Login không thanh cong",
								Toast.LENGTH_SHORT).show();
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}

			}
		}.execute(params);
	}

	/**
	 * check editext Username cannot empty
	 * 
	 * @return false if username is empty
	 */
	private Boolean checkUserName() {
		mUsername = edtUsername.getText().toString();
		if (mUsername.equals("") || mUsername.equals(null)) {
			Toast.makeText(mContext,
					getResources().getString(R.string.username_invalid),
					Toast.LENGTH_SHORT).show();
			return false;
		}
		return true;
	}

	/**
	 * check internet connection
	 * 
	 * @return true if internet avaialbe
	 */
	private Boolean checkInternetConnection() {
		mDetector = new ConnectionDetector(mContext);
		if (mDetector.isConnectingToInternet()) {
			return true;
		}
		Toast.makeText(mContext, "Internet is not available",
				Toast.LENGTH_SHORT).show();
		return false;
	}

	/**
	 * check editext password cannot empty
	 * 
	 * @return false if password is empty
	 */
	private Boolean checkPassword() {
		mPassword = edtPassword.getText().toString();
		if (mPassword.equals("") || mPassword.equals(null)) {
			Toast.makeText(mContext,
					getResources().getString(R.string.password_invalid),
					Toast.LENGTH_SHORT).show();
			return false;
		}
		return true;
	}

	/**
	 * get form widget
	 */
	private void init() {
		edtUsername = (EditText) findViewById(R.id.edtUsername);
		edtPassword = (EditText) findViewById(R.id.edtPassword);
		btnSignin = (Button) findViewById(R.id.btnLogin);
		btnSignup = (Button) findViewById(R.id.btnSignUp);
		btnForgetPassowrd = (Button)findViewById(R.id.btResetPassword);
		
		mDialog = new Dialog(mContext);
		mDialog.setCanceledOnTouchOutside(true);
		mDialog.setTitle(getResources().getString(R.string.forget_password));
		mDialog.setContentView(R.layout.activity_forget_password);
		final EditText etEmail = (EditText) mDialog.findViewById(R.id.etForgetPasswordEmail);
		Spinner spinQuestion = (Spinner)mDialog.findViewById(R.id.spinForgetPassword);
		//set adapter for spinner
		setAdapter(spinQuestion);
		final EditText etAnswer =(EditText)mDialog.findViewById(R.id.etForgetPasswordAnswer);
		Button btCancel = (Button)mDialog.findViewById(R.id.btForgetPasswordCancel);
		Button btSubmit = (Button)mDialog.findViewById(R.id.btForgetPassword);
		btCancel.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				mDialog.dismiss();
			}
		});
		btSubmit.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				//test register GCM
				new RegisterGoogleCM(ActivityLogin.this).registerGCM();
				
				String Email = etEmail.getText().toString().trim();
				String Answer = etAnswer.getText().toString().trim();
				if(Email.equals("")||Email.equals(null)){
					return;
				}
				if(Answer.equals("")||Answer.equals(null)){
					return;
				}
				new AsyncTaskForgetPassword().execute(Email,Answer);
			}
		});
	}
	int idQuestion;
	/**
	 * set adapter for spinnger
	 * @param spinQuestion
	 */
	private void setAdapter(Spinner spinQuestion) {
		String arrSecretQuestion[] = { "TrÆ°á»�ng THPT cá»§a báº¡n lÃ  gÃ¬?",
				"Ä�á»™i bÃ³ng yÃªu thÃ­ch cá»§a báº¡n lÃ  gÃ¬?",
				"MÃ´n thá»ƒ thao yÃªu thÃ­ch cá»§a báº¡n lÃ  gÃ¬?",
				"MÃ´n há»�c báº¡n ghÃ©t nháº¥t lÃ  gÃ¬?" };
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(mContext,
				android.R.layout.simple_spinner_item, arrSecretQuestion);
		adapter.setDropDownViewResource(android.R.layout.simple_list_item_single_choice);
		spinQuestion.setAdapter(adapter);
		spinQuestion.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				idQuestion = arg2;
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				
			}
		});
	}
	class AsyncTaskForgetPassword extends AsyncTask<String, Void, Void>{
		ProgressDialog pd;
		int success;
		@Override
		protected void onPreExecute() {
			pd = new ProgressDialog(mContext);
			pd.setMessage("Sending...");
			pd.show();
			super.onPreExecute();
		}
		@Override
		protected Void doInBackground(String... params) {
			
			String resString = new RequestDataFromServer().requestResetPassword(params[0],params[1],idQuestion);
			
			try {
				JSONObject json = new JSONObject(resString);
				success = json.getInt("success");
			} catch (JSONException e) {
				e.printStackTrace();
			}
			return null;
		}
		@Override
		protected void onPostExecute(Void result) {
			if(success!=1){
				Toast.makeText(mContext, "No reset password, Try again your email or answer!",Toast.LENGTH_LONG).show();
			}else{
				Toast.makeText(mContext, "Success! Please check your mail",Toast.LENGTH_LONG).show();
				mDialog.dismiss();
			}
			pd.dismiss();
			super.onPostExecute(result);
		}
		
	}
}
